package com.bodacn.packapp;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import androidx.fragment.app.Fragment;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * A simple {@link Fragment} subclass.
 */
public class FragmentB extends Fragment implements View.OnClickListener {
    //用于将Activity中的参数传给Fragment
    private Map<String,Object> fragmentParams=new HashMap<String,Object>();
    //用于与主Activity通讯;
    private Handler mainHandler;
    public static final int msgTypeDetail = 1001;
    public static final int msgERRINFO=1002;
    public static final int msgTypeGroup=1003;
    private static final int MSG_ERROR=9005;
    //全局变量
    Toast curToast;
    String selectWorkGroup;
    String curDepart,curDepartNo,curLoginUserNo,curLoginUser,curServiceUrl="",curTermNo="00000",curServiceDir,CPUID;
    EditText edt_WorkGroup,edt_WorkDate;
    Button btn_SelectGroup,btn_PriorDay,btn_NextDay;
    ListView detailList;
    JSONArray detailJSON,departJSON,resultJSON;
    private EditText editA_startDate, editA_endDate;
    //判断是否为数字，不然不转
    public static boolean isNumeric(String str){
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public FragmentB() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //得到Activity的Handler,用于发消息给主Activity;
        MainActivity activity=(MainActivity) getActivity();
        mainHandler=activity.mainHandler;
        curDepart=activity.curDepart;
        //加接口监听
        activity.setTransParamsListenerB(new MainActivity.OnTransParamsListenerB() {
            @Override
            public void TransParams(Map<String, Object> mParams) {
                if (mParams!=null) {
                    try {
                        String paramComm= mParams.get("ParamComm").toString();
                        if (paramComm=="LoginParam")
                        {
                            Log.d("FragmentB","LoginParam------------------>1");
                            //传递登陆参数信息;
                            curLoginUserNo=mParams.get("LoginUserNo").toString();
                            curLoginUser=mParams.get("LoginUser").toString();
                            curServiceUrl=mParams.get("ServiceUrl").toString();
                            curServiceDir=mParams.get("ServiceDir").toString();
                            curDepartNo=mParams.get("DepartNo").toString();
                            curDepart=mParams.get("Depart").toString();
                            curTermNo=mParams.get("TermNo").toString();
                            CPUID=mParams.get("CPUID").toString();
                            Log.d("FragmentB","LoginParam------------------>2");
                            refreshDepartData();
                            //获取当天数据;
                            SimpleDateFormat sj = new SimpleDateFormat("yyyy-MM-dd");
                            Date d = new Date(System.currentTimeMillis());
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(d);
                            queryDetail(curDepart,sj.format(calendar.getTime()));
                        }


                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_b, container, false);
        InitView(root);
        System.out.println("fragment_a_onCreateView");
        return root;
    }
    //初始化;
    public void InitView(View view){
        //置日期初始值;
        edt_WorkDate=(EditText)view.findViewById(R.id.edt_WorkDate);
        Date curDate = new Date(System.currentTimeMillis());
        edt_WorkDate.setText(DateFormat.format("yyyy-MM-dd", new Date(curDate.getTime())));
        edt_WorkDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {final Calendar calendar = Calendar.getInstance();
                final DatePickerDialog mDialog = new DatePickerDialog(getContext(), null, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                mDialog .setButton(DialogInterface.BUTTON_POSITIVE,"完成",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DatePicker datePicker = mDialog.getDatePicker();
                        int year = datePicker.getYear();
                        int month = datePicker.getMonth();
                        int day = datePicker.getDayOfMonth();
                        calendar.set(year,month,day);
                        edt_WorkDate.setText(DateFormat.format("yyyy-MM-dd", calendar));
                        queryDetail(edt_WorkGroup.getText().toString(),edt_WorkDate.getText().toString());

                    }
                });
                mDialog.setButton(DialogInterface.BUTTON_NEGATIVE,"取消",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        System.out.println("cancel~~cancel~~");
                    }
                });
                mDialog.setTitle("选择查询日期");
                mDialog.show();

            }
        });
        detailList=(ListView)view.findViewById(R.id.detailList);
        edt_WorkGroup=(EditText)view.findViewById(R.id.edt_WorkGroup);
        edt_WorkGroup.setText(curDepart);
        btn_SelectGroup=(Button)view.findViewById(R.id.btn_SelectGroup);
        btn_SelectGroup.setOnClickListener(this);
        btn_NextDay=(Button)view.findViewById(R.id.btn_NextDay);
        btn_NextDay.setOnClickListener(this);
        btn_PriorDay=(Button)view.findViewById(R.id.btn_PriorDay);
        btn_PriorDay.setOnClickListener(this);
        //初始提醒;
        curToast = Toast.makeText(getActivity(), "", Toast.LENGTH_SHORT);

    }

    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    //刷新订单初始化列表;
    private void refreshDepartData()
    {
        try {
            departJSON=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //执行SQL过程
        String SqlComm="Exec KeyPoint_Pack_GetDepart @TermNo='" + curTermNo + "',@WorkGroup='" + edt_WorkGroup.getText().toString() + "',@UserNo='"+curLoginUserNo+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);

    }

    @Override
    public void onClick(View v) {
        hideIM(v);
        switch (v.getId()){
            case R.id.btn_SelectGroup:
                showSelectGroup();
                break;
            case R.id.btn_PriorDay:
                try {
                    SimpleDateFormat sj = new SimpleDateFormat("yyyy-MM-dd");
                    String today = edt_WorkDate.getText().toString();
                    Date d = null;
                    d = sj.parse(today);
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(d);
                    calendar.add(Calendar.DATE, -1);
                    edt_WorkDate.setText(sj.format(calendar.getTime()));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                //刷新数据
                queryDetail(edt_WorkGroup.getText().toString(),edt_WorkDate.getText().toString());
                break;
            case R.id.btn_NextDay:
                try {
                    SimpleDateFormat sj = new SimpleDateFormat("yyyy-MM-dd");
                    String today = edt_WorkDate.getText().toString();
                    Date d = null;
                    d = sj.parse(today);
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(d);
                    calendar.add(Calendar.DATE, +1);
                    edt_WorkDate.setText(sj.format(calendar.getTime()));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                //刷新数据
                queryDetail(edt_WorkGroup.getText().toString(),edt_WorkDate.getText().toString());
                break;
            default:
                break;
        }
    }

    //显示工序选择
    private void showSelectGroup(){
        selectWorkGroup="";
        //创建布局
        LayoutInflater inflater=getActivity().getLayoutInflater();
        final View select_proc=inflater.inflate(R.layout.select_workgroup, null);
        //Activity.findViewById最终还是会调用View.findViewById
        //因为在Activity的onCreate中一定会先setContentView的
        final GridView selectGrid=(GridView)select_proc.findViewById(R.id.selectGrid);
        final SelectGridAdapter selectGridAdapter=new SelectGridAdapter(getContext());
        selectGrid.setAdapter(selectGridAdapter);
        selectGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    selectWorkGroup=departJSON.getJSONObject(position).getString("Department");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setView(select_proc).setPositiveButton("确定", new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Field field = null;
                        if (selectWorkGroup.length()>0) {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                                field.setAccessible(true );
                                field.set(dialog,true );
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            }
                            catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            //置当前工序名称;
                            edt_WorkGroup.setText(selectWorkGroup);
                        } else {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                                field.setAccessible(true );
                                field.set( dialog,false );
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            }
                            catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            curToast.setText("请通过点击选中需要切换的组别！");
                            curToast.show();
                        }
                    }
                }
        ).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.v("tag","取消");
            }
        }).setTitle("组别选择");
        final AlertDialog dialog =builder.create();
        dialog.show();
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        params.width = 800;
        params.height = 500 ;
        dialog.getWindow().setAttributes(params);
    }



    //订单表格适配器;
    public final class SelectGridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public SelectGridAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return departJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return departJSON.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.select_workgroup_item, null, false);
            convertView.setLayoutParams(new GridView.LayoutParams((int)140,(int)(50)));
            convertView.setBackground(getResources().getDrawable(R.drawable.orderlist_selector));
            try {
                Log.d("msg","getView()----------------------------------------------------->"+position);
                TextView tv = (TextView) convertView.findViewById(R.id.text_selgroup_name);// 显示文字
                if (departJSON.optJSONObject(0).has("Department")==true)
                    tv.setText(departJSON.optJSONObject(position).get("Department").toString());
            } catch (JSONException e) {
                e.printStackTrace();
                curToast.setText(e.getMessage());
                curToast.show();
            }
            Log.d("msg","SelectGridAdapter_position:"+position);
            return convertView;
        }
    }
    //刷新缸布列表;
    private void queryDetail(String workGroupParam,String workDateParam)
    {
        try {
            detailJSON=new JSONArray("[]");
            //清除界面显示内容;
            final DetailListAdapter detailListAdapter = new DetailListAdapter(getActivity());
            detailList.setAdapter(detailListAdapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //执行SQL过程
        String SqlComm="Exec KeyPoint_Pack_Query @TermNO='" + curTermNo + "',@ManuWorkGroup='" + edt_WorkGroup.getText().toString()
                + "',@WorkGroup='" + curDepart+ "',@WorkDate='" + workDateParam+"',@UserNo='"+curLoginUserNo+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }


    /**
     * 定义一个Handler用于接收Fragment发出来的指令
     */
    public Handler fragmentHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg!=null){
                //消息处理;
                System.out.println("收到的消息是："+msg.what);
                int msgId = msg.what;
                switch (msgId) {
                    case MSG_ERROR:
                        Bundle bundle1=msg.getData();
                        curToast.setText(bundle1.getString("HintInfo"));
                        curToast.show();
                        break;
                    case msgTypeDetail:
                        //显示预排单;
                        final DetailListAdapter detailListAdapter = new DetailListAdapter(getActivity());
                        detailList.setAdapter(detailListAdapter);
                        break;
                    case msgERRINFO:
                        System.out.println(resultJSON);
                        MediaPlayer mediaPlayer = MediaPlayer.create(getActivity(),R.raw.warn);
                        mediaPlayer.start();
                        AlertDialog alertDialog = null; // 创建对话框
                        try {
                            alertDialog = new AlertDialog.Builder(getActivity())
                                    .setTitle("系统提示").setMessage(resultJSON.getJSONObject(0).getString("ERRINFO"))
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            return;
                                        }
                                    }).create();
                            alertDialog.show(); // 显示对话框
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        break;

                    default:
                        break;
                }
            }
        }
    };

    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        System.out.println("SQLComm:"+SQLComm);
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try{
                    JSONArray jsonArray  = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    Message msg = new Message();
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        if (jsonArray.optJSONObject(0).has("TypeDetail")==true) {
                            detailJSON = jsonArray;
                            msg.what = msgTypeDetail;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);

                        }else
                        if (jsonArray.optJSONObject(0).has("TypeGroup")==true) {
                            departJSON = jsonArray;
                        }else
                        if (jsonArray.optJSONObject(0).has("ERRINFO")==true) {
                            resultJSON = jsonArray;
                            msg.what = msgERRINFO;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);

                        }
                        if (jsonArray.optJSONObject(0).has("SQLExcept") == true) {
                            //刷新界面;
                            Message errmsg = new Message();
                            Bundle bundle=new Bundle();
                            bundle.putString("HintInfo",jsonArray.optJSONObject(0).getString("SQLMessage"));
                            errmsg.what = MSG_ERROR;
                            errmsg.setData(bundle);
                            fragmentHandler.removeMessages(errmsg.what);
                            fragmentHandler.sendMessage(errmsg);
                        }
                    }
                } catch (Exception e) {
                    //刷新界面;
                    Message errmsg = new Message();
                    Bundle bundle=new Bundle();
                    bundle.putString("HintInfo",e.getMessage());
                    errmsg.what = MSG_ERROR;
                    errmsg.setData(bundle);
                    fragmentHandler.removeMessages(errmsg.what);
                    fragmentHandler.sendMessage(errmsg);
                }
            }

        };
        new Thread(run).start();

    }

    //订单表格适配器;
    public final class DetailListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public DetailListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return detailJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return detailJSON.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.fragment_b_listhead, null, false);
            int pullVatListWidth=parent.getWidth();
            convertView.setLayoutParams(new ListView.LayoutParams((int)pullVatListWidth,(int)(50)));
            int color = getResources().getColor(R.color.text_blue);
            String tmpValue;
            try {
                Log.d("msg","getView()----------------------------------------------------->"+position);
                TextView tv = (TextView) convertView.findViewById(R.id.txt_item_OrderNo);// 显示文字
                tv.setText(detailJSON.optJSONObject(position).get("OrderNo").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_StyleNo);// 显示文字
                tv.setText(detailJSON.optJSONObject(position).get("StyleNo").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_StyleSort);// 显示文字
                tv.setText(detailJSON.optJSONObject(position).get("StyleSort").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_Color);// 显示文字
                tv.setText(detailJSON.optJSONObject(position).get("Color").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_ColorNo);// 显示文字
                tv.setText(detailJSON.optJSONObject(position).get("ColorNo").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_PSXX);// 显示文字
                tv.setText(detailJSON.optJSONObject(position).get("PSXX").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_SewSize);// 显示文字
                tv.setText(detailJSON.optJSONObject(position).get("SewSize").toString());
                tv.setTextColor(color);
                tv = (TextView) convertView.findViewById(R.id.txt_item_PackNum);// 显示文字
                tv.setText(detailJSON.optJSONObject(position).get("PackNum").toString());
                tv.setTextColor(color);

            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","DetailGridAdapter_position:"+position);
            return convertView;
        }
    }

    //清除界面显示内容
    private void clearFormText(){
        /*
        edt_blowno.setText("");
        txt_tp_barcode.setText("");
        txt_orderno.setText("");
        txt_ricelen.setText("");
        txt_colorno.setText("");
        txt_weight.setText("");
        txt_pieceno.setText("");
        txt_fabicno.setText("");
        txt_totalpiece.setText("");
        txt_readypiece.setText("");
        txt_hintinfo.setText("");
        */

    }



    @Override
    public void onStart() {
        super.onStart();

    }
}
